/**
 * ...
 * @author Krzysztof Rozalski
 */

package hapi.util.assets;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.media.Sound;

class FlashLibraryAssetsLoader implements AssetsLoader {

	static var SOUND_CONST_ARGS = [];
	static var BITMAP_DATA_CONST_ARGS = [null, null];
	var cache:AssetsCache;
	
	public function new() {
		cache = new AssetsCache();
	}
	
	public function loadBitmap(src:String):Bitmap {
		return new Bitmap(loadBitmapData(src));
	}
	
	public function loadBitmapData(linkageId:String):BitmapData {
		return resolveAsset(linkageId, cache.bitmapDatas, BITMAP_DATA_CONST_ARGS);
	}
	
	public function loadSound(linkageId:String):Sound {
		return resolveAsset(linkageId, cache.sounds, SOUND_CONST_ARGS);
	}
	
	static function resolveAsset<T>(linkageId:String, cache:Hash<T>, constArgs:Array<Dynamic>):T {
		if (cache.exists(linkageId)) return cache.get(linkageId);
		var clazz:Class<T> = resolveClass(linkageId);
		var result:T = Type.createInstance(clazz, constArgs);
		cache.set(linkageId, result);
		return result;
	}
	
	static function resolveClass<T>(linkageId:String):Class<T> {
		var clazz:Class<T> = cast Type.resolveClass(linkageId);
		if (clazz == null) throw "Cannot resolve class " + linkageId;
		return clazz;
	}
}